package com.weixin.auth;

import java.util.Date;

import com.aischool.routes.RouteMapping;
import com.aischool.service.WeixinUserService;
import com.aischool.utils.DateUtil;
import com.aischool.utils.SysAppEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.weixin.utils.WeiXinUtils;

@RouteMapping(url = "/weixin/auth")
public class WeixinAuthController extends ApiController {
	
	@Inject
	WeixinUserService weixinUserService;
	
	static Log log = Log.getLog(WeixinAuthController.class);

	public void index() {
		int  subscribe=0;
		//用户同意授权，获取code
		String code=getPara("code");
		String state=getPara("state");
		int user_id = 0;
		int my_app_id = 0;
		if (StrKit.notBlank(state) && state.length() > 3) {
			String[] arr1 = state.split("u");
			if (arr1.length == 2) {
				my_app_id = Integer.parseInt(arr1[0].replaceAll("a", ""));
				user_id = Integer.parseInt(arr1[1]);
			}
		}
		if (code!=null && user_id > 0 && my_app_id>0) {
			String appId=ApiConfigKit.getApiConfig().getAppId();
			String secret=ApiConfigKit.getApiConfig().getAppSecret();
			
			// access_token
			SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
			System.err.println(JSONObject.toJSONString(snsAccessToken));
			
			int expires_in = snsAccessToken.getExpiresIn();
			Date expires_time = DateUtil.addSecond(expires_in);
			String token = snsAccessToken.getAccessToken();
			String openId = snsAccessToken.getOpenid();
			String scope = snsAccessToken.getScope();
			
			System.err.println(openId);
			
			if (StrKit.isBlank(openId)) {
				renderText("openId is null");
				return;
			}
			
			// 拉取用户信息  (需scope为 snsapi_userinfo)
			ApiResult apiResult=SnsApi.getUserInfo(token, openId);
			
			log.warn("getUserInfo:"+apiResult.getJson());
			if (apiResult.isSucceed()) {
				JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
				int sex= jsonObject.getIntValue("sex"); //用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				String nickName=jsonObject.getString("nickname");
				String city=jsonObject.getString("city"); //城市
				String province=jsonObject.getString("province"); //省份
				String country=jsonObject.getString("country"); //国家
				String headimgurl=jsonObject.getString("headimgurl"); 
				String unionid=jsonObject.getString("unionid"); 
				
				//获取用户信息判断是否关注
				ApiResult userInfo = UserApi.getUserInfo(openId);
				log.warn(JsonKit.toJson("is subsribe>>"+userInfo));
				
				if (userInfo.isSucceed()) {
					String userStr = userInfo.toString();
					subscribe=JSON.parseObject(userStr).getIntValue("subscribe");
				}
				
				weixinUserService.save(openId, WeiXinUtils.filterWeixinEmoji(nickName), unionid, 
						headimgurl, country, city, province, sex,
						token, expires_time, scope, user_id);
			}
			
			setSessionAttr("openId", openId);
			if (subscribe==0) {
				renderText("请先关注公众号！");
				//redirect(PropKit.get("subscribe_rul"));
			}else {
				//根据state 跳转到不同的页面
				if (my_app_id == SysAppEnum.TEACHER_APP.getId()) {
					redirect("/front/teacher/html/index");
				}else {
					redirect("/front/family/classes");
				}
			}
			
			
		}else {
			renderText("code is  null");
		}
	}
	
}
